import React from 'react'
import Style from './index.scss'
import API from '@common/api'
import { connect } from 'react-redux'
import { notification, Badge } from 'antd'

@connect(store => ({
  userInfo: store.userInfo
}))
class Comments extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      replayContent: '',
      status: +props.thumbsUp.status,
      totalLike: props.thumbsUp.total
    }
  }

  inputChangeHandler = event => {
    this.setState({
      replayContent: event.target.value
    })
  }

  keyPressHandler = async event => {
    if (event.key === 'Enter') {
      if (!this.state.replayContent) {
        notification['error']({
          message: '请输入评论内容'
        })
        return
      }
      let response = API.addDiscuss({
        topicId: this.props.topicId,
        replayContent: this.state.replayContent
      })
      response
        .then(data => {
          notification['success']({
            message: data.message
          })
        })
        .catch(error => {
          notification['error']({ message: error })
        })

      this.setState({
        replayContent: ''
      })
    }
  }

  thumbsUpHandler = async () => {
    await this.setState(value => ({
      status: value.status === 1 ? 0 : 1,
      totalLike: value.status === 1 ? value.totalLike - 1 : value.totalLike + 1
    }))
    let response = await API.topicLike({
      topicId: this.props.topicId,
      status: this.state.status
    })
    notification['success']({
      message: response.message
    })
  }

  render() {
    const { comments } = this.props
    return (
      <div className={Style['comments-section']}>
        <div className="operation">
          <div className="fl-left">
            <Badge
              offset={[-5, 5]}
              count={this.state.totalLike}
              overflowCount={999}
            >
              <span
                className={`favorite ${
                  this.state.status === 1 ? 'active' : ''
                }`}
                onClick={this.thumbsUpHandler}
              />
            </Badge>
            <Badge offset={[-5, 5]} count={comments.length} overflowCount={999}>
              <span className="comments" />
            </Badge>
          </div>

          <div className="fl-right">
            <span className="collect" />
          </div>
        </div>

        <div className="add-comments">
          <input
            type="text"
            className="u-f-black"
            ref="textInput"
            value={this.state.replayContent}
            onChange={this.inputChangeHandler}
            onKeyPress={this.keyPressHandler}
            placeholder="添加评论"
          />
          <span className="more" />
        </div>
      </div>
    )
  }
}

export default Comments
